<?php

class Pldkp_Controller_Plugin_Authorization extends Zend_Controller_Plugin_Abstract
{
    protected $_acl = null;
    
    public function __construct(User_Model_Acl $acl)
    {
        $this->_acl = $acl;
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $allowed = $this->_acl->isUserAllowed(
            $request->getModuleName(), 
            $request->getControllerName(), 
            $request->getActionName()
        );
        
        if (!$allowed) {
            
            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); 
             
            if ($request->isXmlHttpRequest()) {
                // Im afraid this is the best i can come up with ...
                echo Zend_Json::encode(array("status"=>400, "message"=>"Access denied for action:\n" . $request->getPathInfo()));  
                exit(); 
            } else {

                $url = array(
                    'module' => '',
                    'controller' => 'authentication',
                    'action' => 'access-denied',
                    'redirect' => urlencode($request->getPathInfo()),
                );
                
                $router = Zend_Controller_Front::getInstance()->getRouter();
                $url = $router->assemble($url, null, true, true);
                
                $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); 
                $redirector->gotoUrl($url,  array('prependBase' => false));
                exit();
            }
        }
    }
}
